package com.ruoyi.system.util;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * @ClassDescription:
 * @Author: admin
 * @Created: 2025/3/3 17:42
 */

@Slf4j
public class CommonUtil {

    public static void insertCommonData(Object obj) {
        try {
            Class<?> aClass = obj.getClass();
            Class<?> superclass = aClass.getSuperclass();
            Field createTime = superclass.getDeclaredField("createTime");
            createTime.setAccessible(true);
            createTime.set(obj, new Date());

            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null) {
                Field createBy = superclass.getDeclaredField("createBy");
                createBy.setAccessible(true);
                createBy.set(obj, SecurityUtils.getLoginUser().getUsername());
            }

        } catch (Exception e) {
            log.info("保存插入时间和更新人失败：", e);
        }
    }

    public static void updateCommonData(Object obj) {
        try {
            Class<?> aClass = obj.getClass();
            Class<?> superclass = aClass.getSuperclass();
            Field createTime = superclass.getDeclaredField("updateTime");
            createTime.setAccessible(true);
            createTime.set(obj, new Date());

            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null) {
                Field createBy = superclass.getDeclaredField("updateBy");
                createBy.setAccessible(true);
                createBy.set(obj, SecurityUtils.getLoginUser().getUsername());
            }

        } catch (Exception e) {
            log.info("更新插入时间和更新人失败：", e);
        }
    }
}
